//
//  YHHomeList.swift
//  XLWB
//
//  Created by key on 16/6/27.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class YHHomeList: NSObject {
    
    //MARK: - 模型对象属性
    // 微博创建时间
    var created_at: String?
    
    // 微博ID
    var id: Int64 = 0
    
    // 微博信息内容
    var textAttr: NSMutableAttributedString?
    var text: String? {
        
        didSet {
            
            textAttr = getTextStr(text ?? "")
        }
    }
    
    
    //  微博来源
    var sourceAttr: NSMutableAttributedString?
    // 微博来源
    var source: String? {
        
        didSet {
            
            sourceAttr = getSoureStr(source)
            
        }
    }
    
    //微博配图信息
    var pic_urls:[YHPictureInfo]?
    
    //用户信息
    var user: YHUserModel?
    
    //转发微博信息
    var retweeted_status: YHHomeList?
    
    // 转发数
    var reposts: String?
    //	int	转发数
    var reposts_count: Int = 0{
        
        didSet{
            
            reposts = getCountString(reposts_count, title: "转发")
            
        }
  
    }
    
    // 评论数
    var comments: String?
    //	int	评论数
    var comments_count: Int = 0{
        
        didSet{
            
            comments = getCountString(comments_count, title: "评论")
            
        }
   
    }
    
    // 赞数
    var attitudes: String?
    //	int	赞数
    var attitudes_count: Int = 0{
        
        didSet{
            
            attitudes = getCountString(attitudes_count, title: "赞")
            
        }
 
    }
    
    //MARK: - 转发 评论 赞 数据判断
    func getCountString(count: Int, title: String) -> String {
        
        if count <= 0 {
            
            return title
        }else if count < 10000 {
            
            return "\(count)"
            
        }else{
            
            let countF = CGFloat(count / 1000) / 10
            
            var countStr = "\(countF)"
            
            if countStr.hasSuffix(".0") {
                
//                countStr = countStr.substringToIndex(countStr.endIndex.advancedBy(-2))
                
                countStr = countStr.stringByReplacingOccurrencesOfString(".0", withString: "")
                
                
            }
            
            return "\(countStr)万"
        }
        
        
    }
    
    
    
    //MARK: - KVC构造函数 转模
    init(dict: [String : AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        
        if key == "user" {
            
            if let v = value as? [String: AnyObject] {
                
                user = YHUserModel(dict: v)
                
            }else{
                
                print("用户数据错误")
                
            }
            
            
            
        }else if key == "retweeted_status" {
            
            if let v = value as? [String: AnyObject] {
                
                retweeted_status = YHHomeList(dict: v)
                
            }else{
                
                print("转发微博数据错误")
                
            }
            
            
            
        }else if key == "pic_urls" {
            
            if let v = value as? [[String: AnyObject]] {
                
                //转模
                //遍历数组
                var pic_urlsArr: [YHPictureInfo] = [YHPictureInfo]()
                for dict in v {
                    
                    let pic = YHPictureInfo(dict: dict)
                    
                    pic_urlsArr.append(pic)
                }
                
                pic_urls = pic_urlsArr
                
            }else{
                
                print("微博配图数据错误")
                
            }
            
            
        }else{
            
            //不是特定 key值 调用父类的方法
            super.setValue(value, forKey: key)
            
        }
        
    }
    
    override init() {
        super.init()
    }
    
    
    
    
    //MARK: - 网络请求获取数据
    func loadHomeList(since_id: Int64, max_id: Int64, homeListArr: (homeListArr: [YHHomeList]) -> (), failure: (error:NSError?) -> ()) {
        

        YHNetworkTool.sharedTool.loadHomeList(since_id, max_id: max_id, success: { (request) -> () in
            
            //判断获取的数据
            guard let homeList = request!["statuses"] as? [[String : AnyObject]] else {
                
                print("请求数据错误/数据不是指定格式statuses")
                return
            }
            
            //数据正确  进行遍历 转模
            var homeArr: [YHHomeList] = [YHHomeList]()
            for dict in homeList {
                
                //转模
                let homeL = YHHomeList(dict: dict)
                
                //存入数组
                homeArr.append(homeL)
                
            }
            
            //返回模型数据数组到首页 调用闭包
            homeListArr(homeListArr: homeArr)
            
            
            
            }) { (error) -> () in
                
                failure(error: error)
                
                print("首页-->数据获取错误")
                
        }
        
        
    }
    
    
    
    //MARK: 
    override var description: String {
        
        let keys = ["created_at","id","text","source"]
        
        return dictionaryWithValuesForKeys(keys).description
        
    }

    
    
}


extension YHHomeList {
    
    //MARK: - 数据来源封装方法
    //微博来源数据处理
    func getSoureStr(source: String?) -> NSMutableAttributedString{
        
        
        //<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">微博 weibo.com</a>"
        //判断数据是否存在 并且是否是指定格式
        guard let sou = source where sou.containsString("\">") else{
            //未知来源
            
            return getSourceAttr("来自 未知区域")
        }
        
        //来源数据存在
        //对数据进行切割
        let start = sou.rangeOfString("\">")!
        
        let end = sou.rangeOfString("</a>")!
        
        var r = sou.substringWithRange(start.endIndex..<end.startIndex)
        
        r = "来自 \(r)"
        
        return getSourceAttr(r)
        
    }
    
    //生成副文本  给特定字符设置 相关属性
    func getSourceAttr(result: String) -> NSMutableAttributedString{
        
        //创建副文本
        let att = NSMutableAttributedString(string: result)
        
        //获取需要进行特殊设置的字符 范围
        let range = (result as NSString).rangeOfString("来自")
        
        
        //设置字符 相关属性
        att.addAttributes([NSForegroundColorAttributeName: themeColor], range: range)
        
        
        //返回
        return att
        
        
    }
    
    
    
    //MARK: - 微博信息内容 富文本
    func getTextStr(text: String) -> NSMutableAttributedString {
        
        //1.--> 创建富文本
        let resultAtt = NSMutableAttributedString(string: text)
        
        
        //2. --> 正则 遍历信息内容 找出表情
        //  正则格式 \[]\
        //定义一个数组保存 遍历出来的转模后的数据
        var matchArray: [YHMatch] = [YHMatch]()
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, string, range, _) -> Void in
            
            //转模
            let match = YHMatch(string: (string.memory as! String), range: range.memory)
            
            //存入数组
            matchArray.append(match)
            
        }
        
        
        //遍历数组  从后相前编译
        for match in matchArray.reverse() {
            
            
            //获取数据信息
            let emotion = YHEmotionData.shareEmotion.getSearchEmoticon(match.string!)
            
            //创建文本附件
            let att = NSTextAttachment()
            
            //设置图片
            att.image = UIImage(named: "\(emotion?.path ?? "")\(emotion?.png ?? "")", inBundle: YHEmotionData.shareEmotion.emotionBundle, compatibleWithTraitCollection: nil)
            
            //设置bounds
            let wh = UIFont.systemFontOfSize(15).lineHeight
            att.bounds = CGRectMake(0, -4, wh, wh)
            
            //替换原来的文字
            let attr = NSAttributedString(attachment: att)
            resultAtt.replaceCharactersInRange(match.range!, withAttributedString: attr)
            
            
        }
        
        
        return resultAtt
    }
    
}
